<template>
    <el-card class="project-digital-add-card">
        <template #header>
            <div class="flexC" style="justify-content: space-between;">
                <div class="header-title">添加项目</div>
                <div class="header-actions">
                    <el-button link type="primary" :icon="Back" @click="back">返回</el-button>
                </div>
            </div>
        </template>
        <div class="project-form">
            <div class="left-container">
                <el-form ref="FormRef" :rules="Rules" :model="FormData" label-position="top">
                    <el-form-item label="创建时间" prop="createTime">
                        <el-date-picker v-model="FormData.createTime" type="datetime" clearable placeholder="选择日期时间" class="form-input"></el-date-picker>
                    </el-form-item>
                    <el-form-item label="项目名称" prop="name">
                        <el-input v-model="FormData.name" class="form-input" clearable placeholder="请输入项目名称"></el-input>
                    </el-form-item>
                    <el-form-item label="存储位置（请在右边点选）" >
                        <div class="flexC locationRow" v-for="(item,index) in storageLocationList" :key="index">
                            <el-form-item class="form-input3"  :prop="'storageLocationList['+index+'].storageLocation'" :rules="Rules.storageLocation">
                                <div class="locationitem flexC el-card" @click="selectLocaltion(index)">
                                    <el-radio v-model="LocationActive" :value="index" :label="item.index" ></el-radio>
                                    <div class="rowinput">
                                        <p>柜</p>
                                        <el-input-number :precision="0" :min="1"  :controls="false"  v-model="item.cabinetId" @change="changeCabinet(item.cabinetId)" @blur="changeCabinet(item.cabinetId)" :placeholder="cabinetList.length > 1 ? '柜号：1-'+cabinetList.length:''"></el-input-number>
                                    </div>
                                    <div class="rowinput">
                                        <p>层</p>
                                        <el-input-number :precision="0" :min="1"  :readonly="!item.cabinetId || layerLoading" :controls="false" v-model="item.layerIndex" @change="changeLayer(item.layerIndex)" @blur="changeLayer(item.layerIndex)" :placeholder="layerList.length > 1 ? '层号：1-'+layerList.length:' '"></el-input-number>
                                    </div>
                                    <div class="rowinput">
                                        <p>盒</p>
                                        <el-input-number :precision="0" :min="1" :readonly="!item.layerIndex || layerLoading" :controls="false" v-model="item.boxIndex" @change="changeBox(item.boxIndex)" @blur="changeBox(item.boxIndex)" :placeholder="boxList.length > 1 ? '盒号：1-'+boxList.length:''"></el-input-number>
                                    </div>
                                </div>
                            </el-form-item>
                            <div class="operation">
                                <el-button :icon="CirclePlus" type="primary" link v-if="index == 0" @click="AddLocation"></el-button>
                                <el-button :icon="Delete" type="danger" @click="RemoveLocation(index)" link v-else></el-button>
                            </div>
                        </div>
                    </el-form-item>
                </el-form>
                <div align="center" style="margin-top: 60px;">
                    <el-button type="primary" @click="submitProject" :loading="submitLoading">创建项目</el-button>
                </div>
            </div>
            <div class="line"></div>
            <div class="right-container">
                <p class="title">请选择项目文件所在的位置，例如：2号柜-3层-6盒</p>
                <div class="storage-container flex">
                    <div class="storage-cabinet">
                        <p class="title">柜</p>
                        <div class="cabinet-container" v-loading="cabinetLoading">
                            <template v-for="(item,index) in cabinetList" :key="index">
                                <el-tooltip :content="item.remark" :disabled="!item.remark">
                                    <div class="item flexCC" :class="{'active':activeObj.cabinetId == item.name}"  @click="selectCabinet(item, index)">
                                        {{ item.name }}
                                    </div>
                                </el-tooltip>
                            </template>
                            <!--  -->
                        </div>
                    </div>
                    <div class="storage-cabinet" v-if="activeObj.cabinetId" v-loading="layerLoading">
                        <p class="title">层</p>
                        <div class="cabinet-container" >
                            <div class="item flexCC" :class="{'active':activeObj.layerIndex == (layerList.length - index)}" v-for="(item,index) in layerList" :key="index" @click="selectLayer(index)">
                                {{ layerList.length - index }} 
                            </div>
                        </div>
                    </div>
                    <div class="storage-cabinet" v-if="activeObj.cabinetId" v-loading="layerLoading">
                        <p class="title">盒</p>
                        <div class="cabinet-container" >
                            <div class="item flexCC" :class="{'active':activeObj.boxIndex ==  index}" v-for="(item,index) in boxList" :key="index" @click="selectBox(index, item)">{{ index+1 }}</div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </el-card>
</template>

<script setup>
import { useRoute, useRouter } from 'vue-router';
import { computed, onMounted, reactive, ref } from 'vue';
import { CirclePlus, Delete, Back} from '@element-plus/icons-vue';
import { initProjectName, CabinetQuery, LayerQuery, AddProject } from "@/api/project"
import { ElMessage } from 'element-plus';

const FormRef = ref(null);
const cabinetLoading = ref(false);
const submitLoading = ref(false);
const layerLoading = ref(false);
const LocationActive = ref(0);
const FormData = ref({});
const route = useRoute();
const router = useRouter();
const activeObj = ref({});
const cabinetList = ref([]);
const layerList = ref([]);

const boxList = ref([]);
const storageLocationList = ref([
    {
        cabinetId:null,
        layerIndex: null,
        boxIndex: null
    }
]);

const Rules = computed(()=>({
    createTime: [
        { required: true, message: '请选择创建时间', trigger: 'change' }
    ],
    name: [
        { required: true, message: '请输入项目名称', trigger: 'blur' }
    ],
    storageLocation: [
        {
            required: true,
            validator: (rule, value, callback) => {
                
                for (let i = 0; i < storageLocationList.value.length; i++) {
                    const it = storageLocationList.value[i];
                    if(!it.cabinetId) {
                        return callback("请选择柜号");
                    }
                    if(it.cabinetId &&  cabinetList.value.findIndex(item => item.name == it.cabinetId) == -1){
                        return callback("请输入正确的柜号");
                    }
                    if(!it.layerIndex){
                        return callback("请选择层号");
                    }
                    // if(it.layerIndex && it.layerIndex > layerList.value.length){
                    //     return callback("请输入正确的层数");
                    // }
                    if(!it.boxIndex){
                        return callback("请选择盒号");
                    }
                    // if(it.boxIndex && it.boxIndex > boxList.value.length){
                    //     return callback("请输入正确的盒数");
                    // }
                }
                callback();
            }
        }
    ]
}))
onMounted(()=>{
    getProjectName();
    getCabintData();
})
// 获取档案柜
const getCabintData = async () => {
    cabinetLoading.value = true;
    const res = await CabinetQuery();
    cabinetLoading.value = false;
    if(res.errorCode == 0){
        cabinetList.value = res.data;
        if(route.query.cabinetId && route.query.boxId){
            let rowIndex =  cabinetList.value.findIndex(item => item.id == route.query.cabinetId);
            await selectCabinet(cabinetList.value[rowIndex], rowIndex);
            
            let floorIndex = layerList.value.findIndex(it => it.findIndex(item => item.id == route.query.boxId) != -1);
           
            console.log(floorIndex,'floorIndex');
            let boxIndex = layerList.value[floorIndex].findIndex(item => item.id == route.query.boxId);
            await selectLayer(floorIndex);
            await selectBox(boxIndex, layerList.value[floorIndex][boxIndex]);
        }
    }
}
// 选择档案柜
const selectCabinet = async (item, index) => {
    activeObj.value.cabinetId = item.name;
    storageLocationList.value[LocationActive.value].cabinetId = item.name;
    await getLaryerData(item.name);
    activeObj.value.layerIndex = null;
    storageLocationList.value[LocationActive.value].layerIndex = null;
    storageLocationList.value[LocationActive.value].boxIndex = null;
    activeObj.value.boxIndex = null;
}
// 选择层
const selectLayer = (index) => {
    activeObj.value.layerIndex = layerList.value.length - index;
    storageLocationList.value[LocationActive.value].layerIndex = layerList.value.length - index;
    boxList.value = layerList.value[index];
    activeObj.value.boxIndex = null;
    storageLocationList.value[LocationActive.value].boxIndex = null;
}
// 选择盒
const selectBox = (index, item) => {
    activeObj.value.boxIndex = index;
    storageLocationList.value[LocationActive.value].boxIndex = index+1;
    storageLocationList.value[LocationActive.value].boxId = item.id;
    
}
const changeCabinet = async (value) => {
    let name = cabinetList.value?.find(item => item.name == value)?.name
    activeObj.value.cabinetId =  name;
    await getLaryerData(name);
    if(storageLocationList.value[LocationActive.value].layerIndex &&  layerList.value.length != 0){
        activeObj.value.layerIndex = storageLocationList.value[LocationActive.value].layerIndex;
    }
    if(storageLocationList.value[LocationActive.value].boxIndex && boxList.value.length != 0){
        activeObj.value.boxIndex = storageLocationList.value[LocationActive.value].boxIndex;
        storageLocationList.value[LocationActive.value].boxId = boxList.value[activeObj.value.boxIndex].id;
    }
}
const changeLayer = (value) => {
    if(layerList.length == 0 || !activeObj.value.cabinetId){
        ElMessage.warning('请先选择存储位置');
        return;
    }
    activeObj.value.layerIndex = value;
    if(storageLocationList.value[LocationActive.value].boxIndex && boxList.value.length != 0){
        activeObj.value.boxIndex = null;
        storageLocationList.value[LocationActive.value].boxId = null;
    }
    // storageLocationList.value[LocationActive.value].layerIndex = index;
}
const changeBox = (value) => {
    if(boxList.length == 0 || !activeObj.value.cabinetId){
        ElMessage.warning('请先选择存储位置');
        return;
    }
    activeObj.value.boxIndex = value - 1;
    storageLocationList.value[LocationActive.value].boxId = boxList.value[value - 1].id;
    if(storageLocationList.value[LocationActive.value].boxIndex && boxList.value.length != 0){
        // activeObj.value.boxIndex = storageLocationList.value[LocationActive.value].boxIndex;
        storageLocationList.value[LocationActive.value].boxId = boxList.value[activeObj.value.boxIndex].id;
    }
}

const selectLocaltion = async (index) => {
    if(layerLoading.value) return;
    LocationActive.value = index;
    let obj = {...storageLocationList.value[index]};
    if(obj.boxIndex){
        obj.boxIndex = obj.boxIndex - 1;
    }
    if(obj.cabinetId != activeObj.value.cabinetId){
        await getLaryerData(obj.cabinetId);
    }
    activeObj.value = {...obj};
}
// 获取层数 盒数
const getLaryerData =async (name) => {
    if(!name){
       return;
    }
    layerLoading.value = true;
    let result = await LayerQuery({
        cabinetId: cabinetList.value.find(item => item.name == name).id
    });
    layerLoading.value = false;
    if(result.errorCode == 0){
        layerList.value = [];
        for (let i in result.data) {
            layerList.value.unshift(result.data[i])
        }
        // console.log(layerList.value,'layerList.value');
        if(result.data[1]?.length > 0){
            boxList.value = result.data[1];
        }
    }
}

// 获取 项目名称
const getProjectName = async () => {
    const res = await initProjectName();
    if(res.errorCode == 0){
        FormData.value.name = res.data;
        FormData.value.createTime = new Date();
    }
}
const AddLocation = () => {
    storageLocationList.value.push({
        cabinetId:null,
        layerIndex: null,
        boxIndex: null
    })
}
const RemoveLocation = (index) => {
    storageLocationList.value.splice(index,1);
    if(index == LocationActive.value){
        LocationActive.value = LocationActive.value - 1;
        selectLocaltion(LocationActive.value);
    }
}
const submitProject = ()=>{
    FormData.value['storageLocationList'] = [...storageLocationList.value]
    FormRef.value.validate(async valid => {
        if(valid){
            let showNames = storageLocationList.value.map(item => item.cabinetId + '-' + item.layerIndex + '-' + item.boxIndex);
        
            // return console.log(boxids);
            submitLoading.value = true;
            let result = await AddProject({
                name: FormData.value.name,
                createTime: FormData.value.createTime,
                showNames: showNames
            })
            submitLoading.value = false;
            if(result.errorCode == 0){
                ElMessage.success('项目创建成功');
                // router.back();
                sessionStorage.setItem('Router_AddProject', 1);
                router.push({
                    path:"/projectDigital/details",
                    query:{
                        id: result.data.id
                    }
                })
            }else{
                // ElMessage.warning(result.message);
            }
        }
    })
}
const back = () => {
    router.back();
}

</script>

<style lang="scss" scoped>
.project-digital-add-card{
    
    .header-title{
        font-weight: 600;
        font-size: 18px;
    }
    .project-form{
        display: flex;
        overflow: hidden;
        align-items: stretch;
        .line{
            padding-right: 40px;
            margin-left: 40px;
            position: relative;
            &::after{
                content: " ";
                position: absolute;
                top: 60%;
                left: 0;
                transform: translate(-50%, -60%);
                width: 1px; 
                background: #ccc;
                height: 80%;
            }
        }
        .left-container{
            width: 550px;
            display: flex;
            flex-direction: column;
            justify-content: space-between;
            .operation{
                margin-left: 10px;
                :deep(.el-icon){
                    font-size: 20px;
                    cursor: pointer;
                }
            }
            .locationRow+.locationRow{
                margin-top: 20px;
            }
            .locationitem{
                padding: 10px 15px;
                .el-radio {
                    margin-right: 10px;
                }
                .rowinput{
                    margin-right: 10px;
                    p{
                        font-size: 15px;
                        color: #666;
                        text-align: center;
                    }

                   :deep(.el-input-number ){
                      height: 35px;
                      width: 100%;
                      .el-input__inner{
                        width: 83.75px;
                      }
                    }

                }
            }
        }
        .right-container{
            width: 100%;
            overflow: auto;
            padding-bottom: 10px;
            .title{
                text-align: center;
                font-size: 18px;
            }
            .storage-container{
                margin-top: 30px;
                
                .title{
                    padding: 15px 0;
                }
                .storage-cabinet{
                    width: max-content;
                    &+.storage-cabinet{
                        margin-left: 100px;
                    }
                    .cabinet-container{
                        // min-height: 370px;
                        // border: 1px solid rgba($color: #2E54A1, $alpha: 0.7);
                        // min-height: 120px;
                        display: grid;
                        /* 定义2列，每列宽度根据子元素自动调整 */
                        grid-template-columns: auto auto;
                        /* 定义8行，刚好容纳每列8个元素 */
                        grid-template-rows: repeat(8, auto);
                        /* 关键：设置元素按列优先排列 */
                        grid-auto-flow: column;
                        width: fit-content;
                        /* 列之间的间距 */
                        /* column-gap: 10px; */
                        /* 行之间的间距（垂直方向） */
                        /* row-gap: 10px; */
                    }
                }
                .item{
                    padding: 15px 20px;
                    font-size: 18px;
                    cursor: pointer;
                    background: rgba(218,227,245,1);
                    color: #000;
                    border: 1px solid rgba($color: #2E54A1, $alpha: 0.3);
                    &.active{
                        background: rgba($color: #2E54A1, $alpha: 1);
                        color: #fff;
                    }
                    
                }
            }
        }
    }
}
</style>